package com.aviccxzx.smarthome.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.UserModule.AboutAppActivity;
import com.aviccxzx.smarthome.UserModule.AboutUsActivity;
import com.aviccxzx.smarthome.UserModule.ChangePwdActivity;
import com.aviccxzx.smarthome.UserModule.DeviceShareAct;
import com.aviccxzx.smarthome.UserModule.FeedBackActivity;
import com.aviccxzx.smarthome.UserModule.GosUserLoginActivity;
import com.aviccxzx.smarthome.UserModule.HelpActivity;
import com.aviccxzx.smarthome.UserModule.MainAct;
import com.aviccxzx.smarthome.UserModule.MyCenterdetail;
import com.aviccxzx.smarthome.entity.FeedBack;
import com.aviccxzx.smarthome.entity.MsgStateBean;
import com.aviccxzx.smarthome.entity.UserInfo;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.netutil.msg.MsgListener;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.CleanDataUtil;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.aviccxzx.smarthome.utils.PermissionTool;
import com.aviccxzx.smarthome.widget.HeadImageView;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingUserRole;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener;

import java.io.File;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import zxing.CaptureActivity;

import static com.aviccxzx.smarthome.fragment.CamFragment.cams;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.device_macs;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.isSubed;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.mDevice;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.subList;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.tagSet;
import static com.jovision.AppConsts.APP_PATH;


public class SettingFragment extends Fragment implements EasyPermissions.PermissionCallbacks {

    private String cacheSize = "";
    TextView cache_tv;
    CheckBox push_switch, msg_switch;
    LinearLayout device_share_ll;
    private DialogUtil dialogUtilCleanCache;


    HeadImageView user_img;
    SharedPreferences spf = null;
    String uid;
    TextView self_name;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            view = inflater.inflate(R.layout.setting_fragment_lay_v19, container, false);
        }
        return view;

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        StrictMode.setThreadPolicy(new
                StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(
                new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
        setView();
        setListener();
    }


    private void setView() {
        device_share_ll = (LinearLayout) getView().findViewById(R.id.device_share_ll);
        user_img = (HeadImageView) getView().findViewById(R.id.user_img);
        push_switch = (CheckBox) getView().findViewById(R.id.push_switch);
        msg_switch = (CheckBox) getView().findViewById(R.id.msg_switch);
        cache_tv = (TextView) getView().findViewById(R.id.cache_tv);
        self_name = (TextView) getView().findViewById(R.id.self_name);
        spf = getActivity().getSharedPreferences("set", Context.MODE_PRIVATE);
        //        tagSet = new LinkedHashSet<>();
        uid = spf.getString("Uid", "");

        if (mDevice != null && mDevice.getSharingRole() != null && GizDeviceSharingUserRole.GizDeviceSharingOwner.equals(mDevice.getSharingRole())) {
            device_share_ll.setVisibility(View.VISIBLE);
        } else {
            device_share_ll.setVisibility(View.GONE);
        }
        //判断极光推送是否打开
        boolean istag = spf.getBoolean("tagset", true);
        if (istag) {
            //推送打开
            push_switch.setChecked(true);
        } else {
            push_switch.setChecked(false);
        }
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                push_switch.setChecked(false);
//                msg_switch.setChecked(false);
            }
        }, "inhome");
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                push_switch.setChecked(true);
//                msg_switch.setChecked(true);
            }
        }, "outhome");
    }

    public String getVersion() {
        try {
            PackageManager manager = getActivity().getPackageManager();
            PackageInfo info = manager.getPackageInfo(getActivity().getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "无版本信息";
        }
    }

    private void setListener() {
        getView().findViewById(R.id.mycenter_detail_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), MyCenterdetail.class));
            }
        });
        getView().findViewById(R.id.change_pwd_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), ChangePwdActivity.class));
            }
        });
        getView().findViewById(R.id.clean_cash_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //清除缓存
                if (dialogUtilCleanCache == null) {
                    dialogUtilCleanCache = new DialogUtil(getActivity(), true, true, "确定要清除本地缓存 " + cacheSize + " 吗？", "取消", "确定", new DialogUtil.SureInterfance() {

                        @Override
                        public void sureTodo() {
                            CleanDataUtil.cleanExternalCache(getActivity());
                            CleanDataUtil.deleteFilesByDirectory(new File(APP_PATH));
                            cache_tv.setText("0.0字节");
                            Toast.makeText(getActivity(), "成功清除" + cacheSize + " 的缓存", Toast.LENGTH_SHORT).show();
                            dialogUtilCleanCache = null;
                        }

                        @Override
                        public void cancle() {

                        }
                    });
                }
                dialogUtilCleanCache.showCustomDialog();
            }
        });
        getView().findViewById(R.id.feedback_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), FeedBackActivity.class));
            }
        });
        getView().findViewById(R.id.aboutus_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), AboutUsActivity.class));
            }
        });
        getView().findViewById(R.id.friend_share_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), DeviceShareAct.class));
            }
        });

        push_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //打开时
                    /*tagSet.clear();
                    for (int i = 0; i < subList.size(); i++) {
                        tagSet.add(subList.get(i).getMacAddress());
                    }
                    tagSet.add(uid);
                    if (mDevice != null) {
                        tagSet.add(mDevice.getMacAddress());
                    }
                    JPushInterface.setTags(getActivity(), 0, tagSet);*/
                    JPushInterface.resumePush(getActivity().getApplicationContext());
                    tagSet.clear();
                    if (cams.size() > 0) {
                        //有摄像头
                        for (int i = 0; i < cams.size(); i++) {
                            tagSet.add(cams.get(i).getYst());
                        }
                    }
                    for (int i = 0; i < subList.size(); i++) {
                        tagSet.add(subList.get(i).getMacAddress());
                    }
                    tagSet.add(uid);
                    if (mDevice != null) {
                        tagSet.add(mDevice.getMacAddress());
                    }
                    JPushInterface.setTags(getActivity(), 0, tagSet);
                    spf.edit().putBoolean("tagset", true).commit();
                } else {
                    //关闭时
                   /* tagSet.clear();
                    tagSet.add(uid);
                    JPushInterface.setTags(getActivity(), 0, tagSet);*/
                    JPushInterface.stopPush(getActivity().getApplicationContext());
                    spf.edit().putBoolean("tagset", false).commit();
                }
            }
        });
       /* msg_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //短信关闭按钮
                if (isChecked) {
                    //打开时
                    RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
                    Call<FeedBack> call = service.setDevicesSwitch(1);
                    call.enqueue(new Callback<FeedBack>() {
                        @Override
                        public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                            if (response != null && response.body() != null) {
                                int code = response.body().getCode();
                                if (code == 4) {
                                    spf.edit().putString("msgSwitch", "open").commit();
                                } else {
                                    App.getApp().showToast("短信打开失败，请重试");
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<FeedBack> call, Throwable t) {

                        }
                    });
                } else {
                    RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
                    Call<FeedBack> call = service.setDevicesSwitch(0);
                    call.enqueue(new Callback<FeedBack>() {
                        @Override
                        public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                            if (response != null && response.body() != null) {
                                int code = response.body().getCode();
                                if (code == 4) {
                                    spf.edit().putString("msgSwitch", "close").commit();
                                } else {
                                    App.getApp().showToast("短信关闭失败，请重试");
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<FeedBack> call, Throwable t) {

                        }
                    });
                }
            }
        });*/
        getView().findViewById(R.id.unlogin_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new DialogUtil(getActivity(), true, true, "确定要退出吗？", "取消", "确定", new DialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo() {
                        /*tagSet.clear();
                        tagSet.add(uid);
                        JPushInterface.setTags(getActivity(), 0, tagSet);*/
                        JPushInterface.stopPush(getActivity().getApplicationContext());
                        spf.edit().putString("UserName", "").commit();
                        spf.edit().putString("PassWord", "").commit();
                        spf.edit().putString("thirdUid", "").commit();
                        spf.edit().putStringSet("tagset", null).commit();
                        spf.edit().putStringSet("newSmoke",null).commit();
                        spf.edit().putStringSet("oldSmoke",null).commit();
                        spf.edit().putString("onekey", "").commit();
                        //使设备都处于离家模式
                        onekey(0);
                        spf.edit().putString("Uid", "").commit();
                        spf.edit().putString("Token", "").commit();
                        spf.edit().putString("addMac", "").commit();
                        spf.edit().putString("msgSwitch", "").commit();
                        spf.edit().putBoolean("tagset",true).commit();
                        spf.edit().putString("Imei", "").commit();

                                                spf.edit().clear().commit();
                        isSubed = true;
                        if (mDevice!=null){
                            mDevice.setListener(msubListener);
                            mDevice.setSubscribe(false);
                        }
                        getActivity().finish();
                        Intent intent = new Intent(getActivity(), GosUserLoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void cancle() {
                    }
                }).showCustomDialog();
            }
        });
        getView().findViewById(R.id.scan_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    cameraTask();
                } else {
                    if (PermissionTool.isCameraCanUse()) {
                        openCamera();
                    } else {
                        // 当前APP没有摄像头权限弹层，或者其他相关提示
                        new AppSettingsDialog.Builder(getActivity(), getActivity().getResources().getString(R.string.camera_show))
                                .setTitle("权限申请")
                                .setPositiveButton("确认")
                                .setNegativeButton("取消", null /* click listener */)
                                .setRequestCode(REQUEST_CAMERA_PERM)
                                .build()
                                .show();
                    }
                }
            }
        });
        getView().findViewById(R.id.help_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //帮助
                startActivity(new Intent(getActivity(), HelpActivity.class));
            }
        });
        getView().findViewById(R.id.about_app_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //关于APP
                startActivity(new Intent(getActivity(), AboutAppActivity.class));
            }
        });
    }

    public void onekey(final int value) {
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<FeedBack> call = service.disarmAllSwitch(device_macs, value);
        call.enqueue(new Callback<FeedBack>() {
            @Override
            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                if (response != null && response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 4) {
                        if (value == 1) {
                            spf.edit().putString("onekey", "close").commit();
                        } else {
                            spf.edit().putString("onekey", "open").commit();
                        }
                    } else {
                    }
                }
            }

            @Override
            public void onFailure(Call<FeedBack> call, Throwable t) {

            }
        });
    }

    // 实现回调
    GizWifiDeviceListener msubListener = new GizWifiDeviceListener() {
        @Override
        public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice
                device, boolean isSubscribed) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 订阅或解除订阅成功
            } else {
                // 失败
            }
        }
    };

    /**
     * 请求CAMERA权限码
     */
    public static final int REQUEST_CAMERA_PERM = 101;

    /**
     * EsayPermissions接管权限处理逻辑
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @AfterPermissionGranted(REQUEST_CAMERA_PERM)
    public void cameraTask() {
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            //            openCamera();
            if (PermissionTool.isCameraCanUse()) {
                openCamera();
            } else {
                // 当前APP没有摄像头权限弹层，或者其他相关提示
                new AppSettingsDialog.Builder(getActivity(), "当前App需要申请拍照权限,需要打开设置页面么?")
                        .setTitle("权限申请")
                        .setPositiveButton("确认")
                        .setNegativeButton("取消", null /* click listener */)
                        .setRequestCode(REQUEST_CAMERA_PERM)
                        .build()
                        .show();
            }
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要请求拍照权限",
                    REQUEST_CAMERA_PERM, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //        Toast.makeText(getActivity(), "执行onPermissionsGranted()...", Toast.LENGTH_SHORT).show();
        //        openCamera();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        //        Toast.makeText(getActivity(), "执行onPermissionsDenied()...", Toast.LENGTH_SHORT).show();
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getActivity().getResources().getString(R.string.camera_show))
                    .setTitle("权限申请")
                    .setPositiveButton("确认")
                    .setNegativeButton("取消", null /* click listener */)
                    .setRequestCode(REQUEST_CAMERA_PERM)
                    .build()
                    .show();
        }
    }

    private void openCamera() {
        //扫一扫
        Intent intent = new Intent(getActivity().getApplication(), CaptureActivity.class);
        intent.putExtra("from", "setting");
        startActivityForResult(intent, 222);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == 222) {
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    App.getApp().showToast("请扫描正确的二维码");
                    return;
                }
                String sharecode = bundle.getString("mac", "");
                if (!TextUtils.isEmpty(sharecode)) {
                    if (resultCode == 117) {
                        MsgCenter.fireNull("share", sharecode);
                        MainAct mainAct = (MainAct) getActivity();
                        mainAct.gotoDevice();
                    } else if (resultCode == 116) {
                        MsgCenter.fireNull("camShare", sharecode);
                        MainAct mainAct = (MainAct) getActivity();
                        mainAct.gotoCam();
                    }
                } else {
                    App.getApp().showToast("请扫描正确的二维码");
                }

            } else {
                App.getApp().showToast("请扫描正确的二维码");
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            cacheSize = CleanDataUtil.getCacheSize(new File(APP_PATH));
            if (cacheSize != null) {
                cache_tv.setText("" + cacheSize + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        setName();
        getHeadImg();
        spf = getActivity().getSharedPreferences("set", Context.MODE_PRIVATE);
        /*String msgswitch = spf.getString("msgSwitch", "");
        if (TextUtils.isEmpty(msgswitch)) {
            getMsgState();
        } else {
            if (msgswitch.equals("open")) {
                msg_switch.setChecked(true);
            } else if (msgswitch.equals("close")) {
                msg_switch.setChecked(false);
            }
        }*/
        if (mDevice != null && mDevice.getSharingRole() != null && GizDeviceSharingUserRole.GizDeviceSharingOwner.equals(mDevice.getSharingRole())) {
            device_share_ll.setVisibility(View.VISIBLE);
        } else {
            device_share_ll.setVisibility(View.GONE);
        }
    }

    public void getMsgState() {
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<MsgStateBean> call = service.getDeviceSwitchList();
        call.enqueue(new Callback<MsgStateBean>() {
            @Override
            public void onResponse(Call<MsgStateBean> call, Response<MsgStateBean> response) {
                if (response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 200) {
                        List<MsgStateBean.DataBean> list = response.body().getData();
                        if (list != null && list.size() > 0) {
                            for (MsgStateBean.DataBean bean : list) {
                                if (bean.getMessageSwitch() == 1) {
                                    //开关打开
                                    msg_switch.setChecked(true);
                                    spf.edit().putString("msgSwitch", "open").commit();
                                } else {
                                    //开关关闭
                                    msg_switch.setChecked(false);
                                    spf.edit().putString("msgSwitch", "close").commit();
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<MsgStateBean> call, Throwable t) {

            }
        });
    }

    public void setName() {
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<UserInfo> call = service.getinfo(uid);
        call.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
                if (response.body() != null && response.body().getData() != null) {
                    if (response.body().getData().getUname() != null) {
                        self_name.setText(response.body().getData().getUname().toString());
                    }
                }
            }

            @Override
            public void onFailure(Call<UserInfo> call, Throwable t) {

            }
        });
    }

    public void getHeadImg() {
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<ResponseBody> call = service.getImage();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.body().byteStream()!=null){
                    Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                    if (bitmap!=null){
                        user_img.setBackgroundResource(0);
                        user_img.setImageBitmap(bitmap);
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }
}

